package meijuli.com.join51.business.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.jhx.common.cache.SimpleCache;
import com.jhx.common.http.ApiManager;
import com.jhx.common.http.HttpRequest;
import com.jhx.common.http.HttpResponse;
import com.jhx.common.http.ResponseCallback;
import com.jhx.common.model.User;
import com.jhx.common.utils.Constants;
import com.jhx.common.utils.UserManager;
import com.jhx.common.widget.CommonDialog;
import java.util.ArrayList;
import java.util.List;
import meijuli.com.join51.business.R;
import meijuli.com.join51.business.adapter.CustomAdapter;
import meijuli.com.join51.business.adapter.CustomHolder;
import meijuli.com.join51.business.model.PlatformDiscount;
import meijuli.com.join51.business.service.ApiService;
import retrofit2.Call;

/**
 * 平台扣点
 *
 * @author Wizong 2017-05-19 13:09
 */
public class PlatformDiscountActivity extends BaseActivity {
    TextView mToolbarTitle;
    TextView mDiscountHint;
    RecyclerView mRecycleDiscount;
    Button btnDiscountSure;
    Toolbar mToolbar;

    private User user;
    private TextView mMenuSave;
    private List<PlatformDiscount.Discount> mDiscountList;
    private CustomAdapter<PlatformDiscount.Discount> mAdapter;
    private List<PlatformDiscount.Discount> mSelectList;
    public static int SETTING_ACTIVITY = 1;
    public static int MAIN_ACTIVITY = 0;
    public static String KEY_FROM = "from";
    private int fromActivity = 0;
    private Call<HttpResponse<PlatformDiscount>> mCall;
    private Call<HttpResponse<String>> call;

    public static void start(Activity activity, int from) {
        Intent intent = new Intent(activity, PlatformDiscountActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
        intent.putExtra(KEY_FROM, from);
        activity.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_platform_discount);
        mToolbarTitle = findViewById(R.id.toolbar_title);
        mDiscountHint = findViewById(R.id.text_discount_hint);
        mRecycleDiscount = findViewById(R.id.recycle_platform_discount);
        btnDiscountSure = findViewById(R.id.btn_discount_sure);
        mToolbar = findViewById(R.id.toolbar);
        initToolBar();
        btnDiscountSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(mSelectList.size() > 0) {
                    PlatformDiscount.Discount platformDiscount = mSelectList.get(0);
                    SimpleCache.Companion.put(PlatformDiscount.discontId, platformDiscount.getDmId());
                    UserManager.get().setDiscount(platformDiscount.getDiscountNum());
                    User user = UserManager.get().getUser();
                    user.setDiscountId(platformDiscount.getDmId());
                    user.setIsDiscount(Constants.DISCOUNT_SET);
                    UserManager.get().setUser(user);
                    Intent intent = new Intent(PlatformDiscountActivity.this, ConfirmActivity.class);
                    startActivity(intent);
                }
            }
        });
        initData();
        initView();
    }

    private void initView() {
//        if (fromActivity == MAIN_ACTIVITY)
            btnDiscountSure.setVisibility(View.VISIBLE);
            btnDiscountSure.setEnabled(false);
//        } else {
//            btnDiscountSure.setVisibility(View.GONE);
//            mToolbarTitle.setText(R.string.platform_set_discount);
//            mToolbar.setNavigationIcon(R.mipmap.icon_back_white);
//            mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View view) {
//                    finish();
//                }
//            });
//            mToolbar.inflateMenu(R.menu.menu_save);
//            mMenuSave = mToolbar.findViewById(R.id.menu_save);
//            mMenuSave.setTextColor(ContextCompat.getColor(PlatformDiscountActivity.this,
//                    R.color.gray_bg));
//            mToolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
//                @Override
//                public boolean onMenuItemClick(MenuItem item) {
//                    if (item.getItemId() == R.id.menu_save)  {
//                        if(mSelectList.size() > 0) {
//                            saveClick();
//                        } else {
//                            ToastUtil.getInstance().showToast("请选择平台扣点~");
//                        }
//                    }
//                    return false;
//                }
//            });
//        }
    }

    private void saveClick() {
        final CommonDialog dialog = new CommonDialog(this);
        dialog.setMessage("您确定要更改折扣率？");
        dialog.setOnClickListener(new CommonDialog.OnClickListener() {
            @Override
            public void onConfirmClick(View view) {
                submitDiscount();
            }

            @Override
            public void onCancelClick(View view) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    private void initData() {
        fromActivity = getIntent().getIntExtra(KEY_FROM, MAIN_ACTIVITY);
        user = UserManager.get().getUser();
        mDiscountList = new ArrayList<>();
        mSelectList = new ArrayList<>();
        getPlatformDiscount();
    }

    private void getPlatformDiscount() {
        mCall = ApiManager.get().getApiService(ApiService.class).getPlatformDiscount();
        HttpRequest.getRequest().autoRecycle(this).start(mCall, new ResponseCallback<PlatformDiscount>() {

            @Override
            public void onSuccess(String url, PlatformDiscount data) {
                if(data == null || data.getBusinessDiscountRule() == null) {
                    return;
                }
                mDiscountList = data.getBusinessDiscountRule();
                if (fromActivity == MAIN_ACTIVITY) {
                    mDiscountHint.setText(data.getTips_after_auth());
                } else {
                    mDiscountHint.setText(data.getTips_setting());
                }
//                for (PlatformDiscount.Discount platformDiscount : mDiscountList) {
//                    if (user.getDiscountId() == platformDiscount.getId()) {
//                        mSelectList.clear();
//                        mSelectList.add(platformDiscount);
//                    }
//                }
                setDiscountRecycleView();
            }
        });
    }

    private void setDiscountRecycleView() {
        if (mRecycleDiscount == null || mDiscountList.size() <= 0) {
            return;
        }

        mAdapter = new CustomAdapter<PlatformDiscount.Discount>(mDiscountList, PlatformDiscountActivity.this,
                R.layout.item_platform_discount, null) {
            @Override
            public void onBindData(CustomHolder holder, int position, final PlatformDiscount.Discount platformDiscount) {
                holder.setText(R.id.text_platform_discount, platformDiscount.getDiscountName());
                FrameLayout itemView = (FrameLayout) holder.getItemView(R.layout.item_platform_discount);

                for (PlatformDiscount.Discount discount : mSelectList) {
                    if (platformDiscount.equals(discount)) {
                        itemView.setBackgroundDrawable(ContextCompat.getDrawable(PlatformDiscountActivity.this,
                                R.drawable.bg_platform_discount_select));
                    } else {
                        itemView.setBackgroundDrawable(ContextCompat.getDrawable(PlatformDiscountActivity.this,
                                R.drawable.bg_platform_discount_normal));
                    }
                }
            }
        };

        mAdapter.setOnItemClickListener(new CustomAdapter.OnItemClickListener() {
            @Override
            public void onClick(View view, int position) {
                PlatformDiscount.Discount discount = mDiscountList.get(position);
                if (!mSelectList.contains(discount)) {
                    mSelectList.clear();
                }
                if (mMenuSave != null) {
                    boolean isEqual = user.getDiscountId() == discount.getDmId();
                    mMenuSave.setEnabled(!isEqual);
                    mMenuSave.setTextColor(ContextCompat.getColor(PlatformDiscountActivity.this,
                            (isEqual ? R.color.gray_bg : R.color.white)));
                }

                mSelectList.add(discount);
                mAdapter.notifyDataSetChanged();
                btnDiscountSure.setEnabled(mSelectList.size() > 0);
            }
        });

        mRecycleDiscount.setLayoutManager(new GridLayoutManager(PlatformDiscountActivity.this, 3));
        mRecycleDiscount.setAdapter(mAdapter);
    }

    private void submitDiscount() {
        if (mSelectList.size() > 0) {
            final PlatformDiscount.Discount platformDiscount = mSelectList.get(0);
            call = ApiManager.get().getApiService(ApiService.class)
                    .updatePlatformDiscount(platformDiscount.getDmId() + "", platformDiscount.getDiscountNum());
            HttpRequest.getRequest().autoRecycle(this).start(call, new ResponseCallback<String>() {

                @Override
                public void onSuccess(String url, String data) {
                    UserManager.get().setDiscount(platformDiscount.getDiscountNum());
                    User user = UserManager.get().getUser();
                    user.setDiscountId(platformDiscount.getDmId());
                    user.setIsDiscount(Constants.DISCOUNT_SET);
                    UserManager.get().setUser(user);
                    if (fromActivity == MAIN_ACTIVITY) {
                        Intent intent = new Intent(PlatformDiscountActivity.this, MainActivity.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                        startActivity(intent);
                    }
                }

            });
        }
    }

    private void initToolBar() {
        mToolbarTitle.setText(R.string.platform_discount);
        mToolbarTitle.setText("绑定银行卡");
        mToolbar.setNavigationIcon(R.mipmap.icon_back_white);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }
}
